package com.mlz.mlzmall.ui.activity.act.order;

import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alipay.sdk.app.PayTask;
import com.android.volley.Request;
import com.mlz.mlzmall.R;
import com.mlz.mlzmall.bean.ResponseOrderInfo;
import com.mlz.mlzmall.bean.ResponseWechatAppPay;
import com.mlz.mlzmall.ui.activity.act.address.postCodeToPCD;
import com.mlz.mlzmall.ui.activity.act.base.NetworkActivity;
import com.mlz.mlzmall.ui.activity.act.base.TopTitleView;
import com.mlz.mlzmall.ui.inter.NetResponses;
import com.mlz.mlzmall.ui.utils.mlz.AliPayResult;
import com.mlz.mlzmall.ui.utils.mlz.ConfigInfo;
import com.mlz.mlzmall.ui.utils.mlz.URL;
import com.mlz.mlzmall.volley.util.JsonUtils;
import com.tencent.mm.sdk.modelpay.PayReq;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;

import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;


public class OrderPayment extends NetworkActivity implements NetResponses {
    // 收货人
    TextView NameOrderPay;
    // 联系方式
    TextView PhoneOrderPay;

    //订单编号
    TextView orderCodePayOrder;
    //详细地址
    TextView detailAddressPayment;
    //实付款
    TextView tvRealOrderPay;
    //支付宝布局
    RelativeLayout LinerLayoutAlipay;
    //微信布局
    RelativeLayout LinerLayoutWechat,LinerLayoutEhking;
    //立即支付
    Button tvImmediateOrderPay;
    // 支付宝支付复选按钮
    CheckBox cbAlipaySeleted;
    // 微信支付复选按钮
    CheckBox cbWechatSeleted;
    //易宝支付复选按钮
    CheckBox cbYeePaySeleted;
    String address11, tag = "OrderPayment";
    Map map = new HashMap();


    private void setViewContent() {
        TopTitleView loginTopTitle = (TopTitleView) findViewById(R.id.login_top_title);
        loginTopTitle.setLeftButtonContent(null, R.mipmap.pic_2_1_btn_back, null);
        loginTopTitle.setTitleButtonContent("订单支付", null, null);
        loginTopTitle.setOnLeftButtonClickListener(new TopTitleView.OnLeftButtonClickListener() {
            @Override
            public void onLeftBtnClick(View button) {
                finish();
                OrderPayment.this.overridePendingTransition(R.anim.right_in,R.anim.right_out);
            }
        });
    }
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.order_payment_activity);
        setNetResponses(this);
        this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        setViewContent();
        // 初始化控件
        InitView();
        // 获取订单号
        String orderCode = OrderPayment.this.getIntent().getStringExtra("orderCode");
        // 订单支付数据加载
        PayOrder(orderCode);
        // 按钮的监听
        Listener(orderCode);
        //  获取可支付类型
        getPayMethod(orderCode);
    }

    private void InitView() {
        // 收货人
        NameOrderPay = (TextView) findViewById(R.id.NameOrderPay);
        // 联系方式
        PhoneOrderPay = (TextView) findViewById(R.id.PhoneOrderPay);
        //订单编号
        orderCodePayOrder = (TextView) findViewById(R.id.orderCodePayOrder);
        //详细地址
        detailAddressPayment = (TextView) findViewById(R.id.detailAddressPayment);
        //实付款
        tvRealOrderPay = (TextView) findViewById(R.id.tvRealOrderPay);
        //支付宝布局
        LinerLayoutAlipay = (RelativeLayout) findViewById(R.id.LinerLayoutAlipay);
        //微信布局
        LinerLayoutWechat = (RelativeLayout) findViewById(R.id.LinerLayoutWechat);
        LinerLayoutEhking = (RelativeLayout) findViewById(R.id.LinerLayoutEhking);
        //立即支付
        tvImmediateOrderPay = (Button) findViewById(R.id.tvImmediateOrderPay);
        // 支付宝支付复选按钮
        cbAlipaySeleted = (CheckBox) findViewById(R.id.cbAlipaySeleted);
        // 微信支付复选按钮
        cbWechatSeleted = (CheckBox) findViewById(R.id.cbWechatSeleted);
        //易宝支付复选按钮
        cbYeePaySeleted = (CheckBox) findViewById(R.id.cbYeePaySeleted);

        // 安装了微信就显示微信支付布局
        if (WXAPIFactory.createWXAPI(OrderPayment.this, ConfigInfo.APP_ID).isWXAppInstalled()) {
            LinerLayoutWechat.setVisibility(View.VISIBLE);
        }
    }

    private void PayOrder(final String orderCode) {
        request(Request.Method.GET, URL.ORDER.DETAIL + "?orderCode=" + orderCode, null, sessionId, tag, 100);
    }

    // 复选按钮、回退箭头、 按钮的监听
    private void Listener(final String orderCode) {
        // 复选按钮的监听
        cbAlipaySeleted.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    cbWechatSeleted.setChecked(false);
                    cbYeePaySeleted.setChecked(false);
                }
            }
        });
        cbWechatSeleted.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    cbAlipaySeleted.setChecked(false);
                    cbYeePaySeleted.setChecked(false);
                }
            }
        });
        cbYeePaySeleted.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    cbAlipaySeleted.setChecked(false);
                    cbWechatSeleted.setChecked(false);
                }
            }
        });


        // 立即支付按钮监听
        tvImmediateOrderPay.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                final Handler handler = new Handler() {
                    @Override
                    public void handleMessage(Message msg) {
                        super.handleMessage(msg);
                        String result = (String) msg.obj;
                        AliPayResult result2 = new AliPayResult(result);
                        result2.getResult();
                        if ("支付成功".equals(result2.getResult())) {
                            Intent intent = new Intent(OrderPayment.this, ExchangePaySuccess.class);
                            intent.putExtra("title", result2.getResult());
                            intent.putExtra("content", result2.getResult());
                            startActivity(intent);
                            finish();
                        }

                    }
                };
                if (cbAlipaySeleted.isChecked() || cbWechatSeleted.isChecked() || cbYeePaySeleted.isChecked()) {
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            RestTemplate restTemplate = new RestTemplate();
                            try {
                                HttpHeaders requestHL = new HttpHeaders();
                                // 设置请求头
                                requestHL.set("Cookie", "JSESSIONID=" + sessionId);
                                map.clear();
                                map.put("orderCode", orderCode);
                                // 选择了微信支付，则执行
                                if (cbWechatSeleted.isChecked()) {
                                    map.put("openId", "");
                                    HttpEntity requestEntityLogin = new HttpEntity(map, requestHL);
                                    ResponseEntity<ResponseWechatAppPay> responseWeChatApp = restTemplate.exchange(URL.PAY.WECHAT.PAY, HttpMethod.POST, requestEntityLogin, ResponseWechatAppPay.class);
                                    Log.i("info", "ResponseWeChatAppPay-->" + responseWeChatApp.getBody().getData().toString());
                                    //请求支付
                                    PayReq req = new PayReq();
                                    IWXAPI api = WXAPIFactory.createWXAPI(OrderPayment.this, null);
                                    // 将该app注册到微信
                                    api.registerApp(ConfigInfo.APP_ID);
                                    // 获取POST请求参数
                                    req.appId = responseWeChatApp.getBody().getData().getAppid();
                                    req.partnerId = responseWeChatApp.getBody().getData().getPartnerid();
                                    req.prepayId = responseWeChatApp.getBody().getData().getPrepayid();
                                    req.nonceStr = responseWeChatApp.getBody().getData().getNoncestr();
                                    req.timeStamp = responseWeChatApp.getBody().getData().getTimestamp();
                                    req.packageValue = responseWeChatApp.getBody().getData().getAppPackage();
                                    req.sign = responseWeChatApp.getBody().getData().getSign();
                                    Log.i("INFO", "发起支付中...");
                                    api.sendReq(req);

                                } else if (cbAlipaySeleted.isChecked()) {
                                    try {
                                        HttpEntity requestEntityLogin = new HttpEntity<>(map, requestHL);
                                        String result = restTemplate.postForObject(URL.PAY.ALIPAY.APPPAY, requestEntityLogin, String.class);
                                        JSONObject object = new JSONObject(result);
                                        JSONObject object1 = object.optJSONObject("data");
                                        String payInfo = object1.optString("payInfo");
                                        //  构造PayTask 对象
                                        PayTask alipay = new PayTask(OrderPayment.this);
                                        // 调用支付接口，获取支付结果
                                        String result2 = alipay.pay(payInfo);
                                        Message message = handler.obtainMessage();
                                        message.obj = result2;
                                        handler.sendMessage(message);

                                    } catch (Exception E) {
                                        System.out.println("alipaySDK::失败---" + E);
                                    }
                                } else if (cbYeePaySeleted.isChecked()) {
                                    // 易宝支付
                                    HttpEntity requestEntityPayE = new HttpEntity(map, requestHL);
                                    final String responseForEking = restTemplate.postForObject(URL.PAY.EHKING.PAY, requestEntityPayE, String.class);
                                    // 跳转到易宝支付页面,发起支付
                                    JSONObject object = new JSONObject(responseForEking);
                                    if (1305 == object.optInt("status")) {
                                        JSONObject object1 = object.optJSONObject("data");
                                        final JSONObject object2 = object1.optJSONObject("map");
                                        runOnUiThread(new Runnable() {
                                            @Override
                                            public void run() {
                                                Intent intentToEhk = new Intent(OrderPayment.this, EhkingActivity.class);
                                                intentToEhk.putExtra("redirectUrl", object2.optString("redirectUrl"));
                                                startActivity(intentToEhk);
                                            }
                                        });
                                    }

                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    }).start();

                    // 恢复按钮功能
                    tvImmediateOrderPay.setEnabled(true);
                } else {
                    Toast.makeText(getBaseContext(), "请选择一种支付方式", Toast.LENGTH_SHORT).show();
                    // 恢复按钮功能
                    tvImmediateOrderPay.setEnabled(true);
                    return;
                }
            }
        });
    }

    //获取可用的支付方式
    private void getPayMethod(final String orderCode) {
        request(Request.Method.GET, URL.COMMON.GET_PAY_METHOD + "?orderCode=" + orderCode, null, sessionId, tag, 200);

    }


    @Override
    public void success(int type, JSONObject jsonObject) {

        JSONObject object = jsonObject.optJSONObject("data");
        switch (type) {
            case 100:
                if (object != null) {
                    ResponseOrderInfo.Data data = JsonUtils.object(object.toString(), ResponseOrderInfo.Data.class);
                    // 更新UI
                    //订单编号
                    orderCodePayOrder.setText(data.getOrderCode());
                    //收货人
                    NameOrderPay.setText(data.getShippingFullname());
                    // 联系方式
                    PhoneOrderPay.setText(data.getShippingTelephone());
                    //详细地址
                    StringBuffer sb = new StringBuffer();
                    int regionCode = data.getShippingRegionCode();
                    postCodeToPCD pcd = new postCodeToPCD(this);
                    sb.append(pcd.province(String.valueOf(regionCode)));
                    sb.append(pcd.city(String.valueOf(regionCode)));
                    sb.append(pcd.district(String.valueOf(regionCode)));
                    sb.append(data.getShippingAddress());
                    address11 = sb.toString();
                    detailAddressPayment.setText(sb.toString());
                    //实付款
                    tvRealOrderPay.setText(String.valueOf(data.getTotal()));
                }

                break;

            case 200:
                JSONArray obj = jsonObject.optJSONArray("data");
                for (int i = 0; i < obj.length(); i++) {
                    JSONObject object1 = obj.optJSONObject(i);
                    int type1 = object1.optInt("type");
                    int payId = object1.optInt("payId");
                    if (type1 != 1) {
                        if(payId == 1){
                            LinerLayoutWechat.setVisibility(View.GONE);
                        }else if(payId == 2){
                            LinerLayoutAlipay.setVisibility(View.GONE);
                        }else if(payId == 3){
                            LinerLayoutEhking.setVisibility(View.GONE);
                        }
                    }
                }
                break;
        }

    }

    @Override
    public void fail() {

    }
}
